<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="format.mobile"
        name="用户名"
        label="手机号"
        required
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请填写正确手机号',
            trigger: 'onChange',
            pattern: /^1[3-9]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="format.code"
        type="password"
        name="密码"
        label="登录密码"
        required
        placeholder="请输入密码"
        :rules="[
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          loading-text="拼命登录中..."
          :disabled="isLoading"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
// import { Notify } from 'vant'
import { myNotify } from '../../utils/Notify'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      format: {
        mobile: '',
        code: ''
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['getToken', 'getRefreshToken']),
    async onSubmit () {
      this.isLoading = true // 按钮的加载状态
      try {
        // 登录接口,是否成功
        const res = await loginAPI(this.format)
        this.isLoading = false
        // 登陆成功,提示信息
        myNotify({ type: 'success', message: '登录成功了哦' })
        // 登录成功,把生成的token值,传给vuex中
        this.getToken(res.data.data.token)
        this.getRefreshToken(res.data.data.refresh_token)
        // 登录成功,跳转主页
        this.$router.replace({
          path: '/layout'
        })
      } catch (err) {
        // 登录失败
        this.isLoading = false
        myNotify({ type: 'danger', message: '登录失败' })
      }
    }
  }
}
</script>

<style lang='less' scoped>
// .van-nav-bar{
//   background-color: #007bff;
// }
// /deep/ .van-nav-bar__title{
//   color:white
// }
</style>
